Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
bignumber.js
Advanced tools
The bignumber.js package is a JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. It allows for high-precision calculations that are necessary when dealing with very large or very small numbers that cannot be accurately represented with JavaScript's native Number type.
Arithmetic Operations
Perform precise arithmetic operations such as addition, subtraction, multiplication, and division.
"use strict"; const BigNumber = require('bignumber.js'); let x = new BigNumber(123.4567); let y = new BigNumber('123456.7e-3'); let z = x.plus(y); console.log(z.toString()); // '246.9134'
Chaining Methods
Allows for method chaining to perform multiple operations sequentially on a BigNumber instance.
"use strict"; const BigNumber = require('bignumber.js'); let result = new BigNumber('111.1111111').plus('0.0000001').times('3').sqrt().toPrecision(10); console.log(result); // '1.732050808'
Comparison
Compare two BigNumber instances to determine the relational state.
"use strict"; const BigNumber = require('bignumber.js'); let a = new BigNumber('2'); let b = new BigNumber('3'); console.log(a.isLessThan(b)); // true
Rounding
Round a BigNumber to a specified number of decimal places.
"use strict"; const BigNumber = require('bignumber.js'); let number = new BigNumber('123.4567'); let rounded = number.toFixed(2); console.log(rounded); // '123.46'
Conversion
Convert a BigNumber to a different base or to a string representation.
"use strict"; const BigNumber = require('bignumber.js'); let number = new BigNumber('123456.789e-3'); let inBase10 = number.toString(10); console.log(inBase10); // '123.456789'
Similar to bignumber.js, decimal.js is a library for arbitrary-precision Decimal arithmetic. It provides a similar API but focuses strictly on decimal numbers, whereas bignumber.js can handle non-decimal (base 2-36) numbers as well.
big.js is another arbitrary-precision arithmetic library. It is smaller and simpler than bignumber.js, but it does not include some of the more advanced features and functions that bignumber.js provides.
mathjs is an extensive math library for JavaScript and Node.js, which includes functionality for arbitrary-precision arithmetic. It offers a wider range of mathematical functions and data types compared to bignumber.js, but it is also larger in size.
A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.
toExponential
, toFixed
, toPrecision
and toString
methods of JavaScript's Number typetoFraction
and a correctly-rounded squareRoot
methodIf a smaller and simpler library is required see big.js.
It's less than half the size but only works with decimal numbers and only has half the methods.
It also does not allow NaN
or Infinity
, or have the configuration options of this library.
See also decimal.js, which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits.
The library is the single JavaScript file bignumber.js (or minified, bignumber.min.js).
<script src='relative/path/to/bignumber.js'></script>
For Node.js, the library is available from the npm registry
$ npm install bignumber.js
var BigNumber = require('bignumber.js');
To load with AMD loader libraries such as requireJS:
require(['path/to/bignumber'], function(BigNumber) {
// Use BigNumber here in local scope. No global BigNumber.
});
In all examples below, var
, semicolons and toString
calls are not shown.
If a commented-out value is in quotes it means toString
has been called on the preceding expression.
The library exports a single function: BigNumber
, the constructor of BigNumber instances.
It accepts a value of type number (up to 15 significant digits only), string or BigNumber object,
x = new BigNumber(123.4567)
y = new BigNumber('123456.7e-3')
z = new BigNumber(x)
x.equals(y) && y.equals(z) && x.equals(z) // true
and a base from 2 to 64 inclusive can be specified.
x = new BigNumber(1011, 2) // "11"
y = new BigNumber('zz.9', 36) // "1295.25"
z = x.plus(y) // "1306.25"
A BigNumber is immutable in the sense that it is not changed by its methods.
0.3 - 0.1 // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1) // "0.2"
x // "0.3"
The methods that return a BigNumber can be chained.
x.dividedBy(y).plus(z).times(9).floor()
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil()
Many method names have a shorter alias.
x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true
x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1 // true
Like JavaScript's number type, there are toExponential
, toFixed
and toPrecision
methods
x = new BigNumber(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
x.toNumber() // 255.5
and a base can be specified for toString
.
x.toString(16) // "ff.8"
There is also a toFormat
method which may be useful for internationalisation
y = new BigNumber('1234567.898765')
y.toFormat(2) // "1,234,567.90"
The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the config
method of the BigNumber
constructor.
The other arithmetic operations always give the exact result.
BigNumber.config({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })
x = new BigNumber(2);
y = new BigNumber(3);
z = x.div(y) // "0.6666666667"
z.sqrt() // "0.8164965809"
z.pow(-3) // "3.3749999995"
z.toString(2) // "0.1010101011"
z.times(z) // "0.44444444448888888889"
z.times(z).round(10) // "0.4444444445"
There is a toFraction
method with an optional maximum denominator argument
y = new BigNumber(355)
pi = y.dividedBy(113) // "3.1415929204"
pi.toFraction() // [ "7853982301", "2500000000" ]
pi.toFraction(1000) // [ "355", "113" ]
and isNaN
and isFinite
methods, as NaN
and Infinity
are valid BigNumber
values.
x = new BigNumber(NaN) // "NaN"
y = new BigNumber(Infinity) // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true
The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
x = new BigNumber(-123.456);
x.c // [ 123, 45600000000000 ] coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign
Multiple BigNumber constructors can be created, each with their own independent configuration which applies to all BigNumber's created from it.
// Set DECIMAL_PLACES for the original BigNumber constructor
BigNumber.config({ DECIMAL_PLACES: 10 })
// Create another BigNumber constructor, optionally passing in a configuration object
BN = BigNumber.another({ DECIMAL_PLACES: 5 })
x = new BigNumber(1)
y = new BN(1)
x.div(3) // '0.3333333333'
y.div(3) // '0.33333'
For futher information see the API reference in the doc directory.
The test directory contains the test scripts for each method.
The tests can be run with Node or a browser. For Node use
$ npm test
or
$ node test/every-test
To test a single method, e.g.
$ node test/toFraction
For the browser, see every-test.html and single-test.html in the test/browser directory.
bignumber-vs-number.html enables some of the methods of bignumber.js to be compared with those of JavaScript's number type.
Version 1.x.x of this library is still supported on the 'original' branch. The advantages of later versions are that they are considerably faster for numbers with many digits and that there are some added methods (see Change Log below). The disadvantages are more lines of code and increased code complexity, and the loss of simplicity in no longer having the coefficient of a BigNumber stored in base 10.
See the README in the perf directory.
For Node, if uglify-js is installed
npm install uglify-js -g
then
npm run build
will create bignumber.min.js.
A source map will also be created in the root directory.
Open an issue, or email
Michael
MIT.
See LICENCE.
isBigNumber
tests.isBigNumber
method.ERRORS
after a BigNumber.another
call (due to parseNumeric
declaration in outer scope).%
issue, see #57 and #102.require('crypto')
- leave it to the user.BigNumber.set
as BigNumber.config
alias.POW_PRECISION
to 0
.toPower
.window.crypto
not assigned to crypto
.crypto
shim.valueOf
and toJSON
, include the minus sign with negative zero.max
, min
, precision
, random
, shift
, toDigits
and truncated
methods.add
, mul
, sd
, sub
and trunc
.another
method to enable multiple independent constructors to be created.0b
, 0o
and 0x
.toExponential
, toFixed
, toFormat
and toPrecision
.CRYPTO
configuration property so cryptographically-secure pseudo-random number generation can be specified.MODULO_MODE
configuration property to enable the rounding mode used by the modulo
operation to be specified.POW_PRECISION
configuration property to enable the number of significant digits calculated by the power operation to be limited.dividedToIntegerBy
, isInteger
and toFormat
methods.isF
, isZ
, toE
, toF
, toFr
, toN
, toP
, toS
.toJSON
and decimalPlaces
methods.toNumber
.sqrt
in all, rather than almost all, cases.FAQs
A library for arbitrary-precision decimal and non-decimal arithmetic
The npm package bignumber.js receives a total of 9,884,068 weekly downloads. As such, bignumber.js popularity was classified as popular.
We found that bignumber.js demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.